import time
import logging
import asyncio
import threading


logger = logging.getLogger(__name__)


class Impetus:
    def __init__(self, master, rate=1):
        self.m = master
        self.rate = rate


    async def _heartbeat(self):
        t0 = time.perf_counter()
        while True:
            for uid, ob in self.m.user_ob.items():
                await ob.heartbeat()

            t0 += self.rate
            dt = t0 - time.perf_counter()
            if dt < 0:
                logger.warning(f'heartbeat delta time: {dt}')
                dt = 0
            #logger.debug(f'heartbeat delta time: {dt}')
            await asyncio.sleep(dt)


    def run(self):
        asyncio.run(self._heartbeat())


    def __call__(self):
        threading.Thread(target=self.run, daemon=True, name='impetus').start()

